import { OnInit, ChangeDetectorRef, Component, ChangeDetectionStrategy, inject } from '@angular/core';
import { ModalHelper, SettingsService, _HttpClient } from '@delon/theme';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzListModule } from 'ng-zorro-antd/list';
import { ChangePasswordComponent } from 'src/app/layout';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';

import { BindEmailComponent } from './bind-emial.component';

@Component({
  selector: 'app-account-profile-security',
  templateUrl: './security.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NzListModule]
})
export class ProfileSecurityComponent implements OnInit {
  user: NzSafeAny;
  securityInfo: NzSafeAny = {};
  protected readonly http = inject(_HttpClient);
  private readonly settings = inject(SettingsService);
  private readonly modal = inject(ModalHelper);
  private readonly changeDetectorRef = inject(ChangeDetectorRef);

  ngOnInit(): void {
    this.user = this.settings.user;
    this.getSecurityInfo();
  }

  changePassword() {
    console.log('change password');
    this.modal.createStatic(ChangePasswordComponent, {}, { drag: true }).subscribe();
  }

  changeEmail() {
    this.modal.createStatic(BindEmailComponent, null, { size: 'md', drag: true }).subscribe(() => {
      this.getSecurityInfo();
    });
  }

  getSecurityInfo() {
    this.http.get(`${Api.BaseUserApi}/security`).subscribe((res: NzSafeAny) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) {
          this.securityInfo = res.data;
          this.changeDetectorRef.markForCheck();
          this.changeDetectorRef.detectChanges();
        }
      }
    });
  }
}
